package com.seeyon.apps.taxFund.event;


import cn.hutool.core.lang.Assert;
import com.seeyon.apps.gkcwplugin.dao.DealDataDao;
import com.seeyon.apps.gkcwplugin.po.FapiaoKjPJPO;
import com.seeyon.apps.gkcwplugin.po.FapiaoKjPO;
import com.seeyon.apps.gkcwplugin.util.BaseConnection;
import com.seeyon.apps.util.CAP4FormKit;
import com.seeyon.cap4.form.bean.FormBean;
import com.seeyon.cap4.form.bean.FormDataMasterBean;
import com.seeyon.cap4.form.bean.FormDataSubBean;
import com.seeyon.cap4.form.bean.FormTableBean;
import com.seeyon.cap4.form.service.CAP4FormManager;
import com.seeyon.ctp.common.AppContext;
import com.seeyon.ctp.common.constants.ApplicationCategoryEnum;
import com.seeyon.ctp.common.exceptions.BusinessException;
import com.seeyon.ctp.organization.bo.V3xOrgDepartment;
import com.seeyon.ctp.organization.bo.V3xOrgMember;
import com.seeyon.ctp.organization.manager.OrgManager;
import com.seeyon.ctp.util.Base64;
import com.seeyon.ctp.workflow.event.AbstractWorkflowEvent;
import com.seeyon.ctp.workflow.event.WorkflowEventData;
import com.seeyon.ctp.workflow.event.WorkflowEventResult;
import com.seeyon.ctp.workflow.util.WorkflowEventConstants.WorkflowEventType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 把生成凭证需要的信息写给浪潮数据库
 */
public class FaPiaoKaiJuPZEvent extends AbstractWorkflowEvent {

    private static final Logger log = LoggerFactory.getLogger(FaPiaoKaiJuPZEvent.class);

    private final CAP4FormManager cap4FormManager;

    private OrgManager orgManager = (OrgManager)AppContext.getBean("orgManager");

    private DealDataDao dealDataDao = (DealDataDao) AppContext.getBean("dealDataDao");

    public FaPiaoKaiJuPZEvent(CAP4FormManager cap4FormManager) {
        this.cap4FormManager = cap4FormManager;
    }


    @Override
    public ApplicationCategoryEnum getAppName() {
        // TODO 自动生成的方法存根
        return ApplicationCategoryEnum.form;
    }

    @Override
    public WorkflowEventType getType() {
        // TODO 自动生成的方法存根
        return WorkflowEventType.Ext;
    }

    @Override
    public String getId() {
        return "FaPiaoKaiJuPZEvent";
    }

    @Override
    public String getLabel() {
        return "发票开具生成凭证";
    }

    /*
     * 节点事件
     *
     */
    @Override
    public synchronized WorkflowEventResult onBeforeFinishWorkitem(WorkflowEventData data) {
        log.info("=========================进入-发票开具申请单生成凭证接口=============================");

        WorkflowEventResult res = new WorkflowEventResult();
        Long memberId = AppContext.getCurrentUser().getId();
        long affairId = data.getAffairId();

        Map<String, Object> map = data.getBusinessData();
        //获取表单的数据
        FormDataMasterBean master = (FormDataMasterBean) map.get("formDataBean");
        Long formId = master.getFormTable().getFormId();
        Long formRecordId = master.getId();

        String url = "/seeyon/collaboration/collaboration.do?method=summary&openFrom=listSent&affairId="
                + affairId;
        String urlCode = null;

        try {
            V3xOrgMember member = orgManager.getMemberById(memberId);

            String ticket = Base64.encodeString(member.getCode());
            log.info("--------------------------ticket:" + ticket);
            url = "http://114.218.158.106:8801/seeyon/login/sso?from=sample&ticket=" + ticket + "&tourl="
                    + URLEncoder.encode(url, "UTF-8");
            urlCode = URLEncoder.encode(url, "UTF-8");
            log.info("--------------------------url:" + url);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            log.error("发票开具凭证回写失败：{}", e.getMessage());
        } catch (BusinessException e) {
            e.printStackTrace();
            log.error("发票开具凭证回写失败：{}", e.getMessage());
        }

        //获取表单的数据
        FormBean formBean = cap4FormManager.getForm(formId, true);

//        FapiaoKjPO fapiaokjPO = dealDataDao.findFapiaoKjPOById(Long.valueOf(formRecordId));
//        log.info("----fapiaokjPO:" + fapiaokjPO);
//        List<FapiaoKjPJPO> pjList = dealDataDao.findFapiaoKjPJPO(Long.valueOf(formRecordId));
//				List<FapiaoKjBankPO> bankList = dealDataDao.findFapiaoKjBankPO(Long.valueOf(formRecordId));
//        log.info("----pjList:" + pjList);
        Connection conn = BaseConnection.getConnection();
        PreparedStatement ps = null;
        int rs = 0;
        log.info("===数据库连接成功===");
        String zbSql = "INSERT INTO OAZJB_ZB (OAZJB_ZB_ID,OAZJB_ZB_BDLX,OAZJB_ZB_BXBM,OAZJB_ZB_SQRQ,"
                + "OAZJB_ZB_HZJE,OAZJB_ZB_LCDZ)"
                + "VALUES (?,?,?,?,?,?)";
        try {

            log.info("====获取prepareStatement===");
            ps = conn.prepareStatement(zbSql);

            log.info("获取到表单Id：{}", formRecordId);
            ps.setLong(1, formRecordId);
            ps.setString(2, "5");
            // 报销部门名称 对应字段field0178
            Long bxbmId = CAP4FormKit.getFieldValue(master, "填表部门", Long.class, null);
            log.info("获取到部门ID：{}", bxbmId);
            ps.setString(3,bxbmId.toString());

            // 填表日期 对应字段field0003
            Date tbrq = CAP4FormKit.getFieldValue(master, "单据日期", Date.class, null);

            if (tbrq != null) {
                java.sql.Date sqrq = new java.sql.Date(tbrq.getTime());
                ps.setDate(4, sqrq);
            } else {
                ps.setDate(4, null);
            }
            // 合计金额小写 field0010
            Double hjje = CAP4FormKit.getFieldValue(master, "合计含税金额", Double.class, null);

            ps.setBigDecimal(5, new BigDecimal(hjje));
            ps.setString(6, url);

            rs = ps.executeUpdate();

            if (rs < 0) {
                return res;
            }

            // 明细表
            log.info("====处理明细表字段===");
            FormTableBean dtlTableBean = CAP4FormKit.getSubTableBeanByDisplay(formBean, "用途金额");
            Assert.notNull(dtlTableBean, "【{}】不存在", "用途金额");
            for (FormDataSubBean subData : master.getSubData(dtlTableBean.getTableName())) {
                String pjSql = "INSERT INTO OAZJB_PJXX (OAZJB_PJXX_ID,OAZJB_PJXX_MXID,OAZJB_PJXX_KPMC,"
                        + "OAZJB_PJXX_KDJE,OAZJB_PJXX_HSJE,OAZJB_PJXX_FPXM)"
                        + "VALUES (?,?,?,?,?,?)";

                ps = conn.prepareStatement(pjSql);
//                ps.setLong(1, row.getFormmainId());
                log.info("明细表Id：{}", subData.getFormmainId());
                ps.setLong(1, subData.getFormmainId());
//                ps.setLong(2, row.getId());
                ps.setLong(2, subData.getId());
                // 用途说明-field0007
                String spmc = CAP4FormKit.getFieldValue(subData, "用途说明", String.class, "0");
                ps.setString(3, spmc);
                // todo 待确认 取数量？
                Double kdje = CAP4FormKit.getFieldValue(subData, "数量", Double.class, Double.valueOf(0));
                ps.setBigDecimal(4, new BigDecimal(kdje));
                // 用途金额
                Double ytje = CAP4FormKit.getFieldValue(subData, "数量", Double.class, null);
                if (ytje == null) {
                    ps.setBigDecimal(5, null);
                }else {
                    ps.setBigDecimal(5, new BigDecimal(ytje));
                }
                // 备注
                String fpxm = CAP4FormKit.getFieldValue(subData, "备注", String.class, null);

                ps.setString(6, fpxm);

                rs = ps.executeUpdate();

                if (rs < 0) {
                    res.setAlertMessage("数据插入中间库失败");
                    return res;
                }
            }
           /* for (FapiaoKjPJPO row : pjList) {
                String pjSql = "INSERT INTO OAZJB_PJXX (OAZJB_PJXX_ID,OAZJB_PJXX_MXID,OAZJB_PJXX_KPMC,"
                        + "OAZJB_PJXX_KDJE,OAZJB_PJXX_HSJE,OAZJB_PJXX_FPXM)"
                        + "VALUES (?,?,?,?,?,?)";

                ps = conn.prepareStatement(pjSql);
                ps.setLong(1, row.getFormmainId());
                ps.setLong(2, row.getId());
                ps.setString(3, row.getKpmc());
                ps.setBigDecimal(4, row.getKdje());
                ps.setBigDecimal(5, row.getHsje());
                ps.setString(6, row.getFpxm());

                rs = ps.executeUpdate();

                if (rs < 0) {
                	res.setAlertMessage("数据插入中间库失败");
                    return res;
                }
            }*/

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      //					for (FapiaoKjBankPO row : bankList) {
//						String htSql = "INSERT INTO OAZJB_HTXX (OAZJB_HTXX_ID,OAZJB_HTXX_MXID,OAZJB_HTXX_XH,"
//								+ "OAZJB_HTXX_FKZH,OAZJB_HTXX_YHKD,OAZJB_HTXX_PZH)"
//								+ "VALUES (?,?,?,?,?,?)";
//
//						ps = conn.prepareStatement(htSql);
//						ps.setLong(1, row.getFormmainId());
//						ps.setLong(2, row.getId());
//						ps.setBigDecimal(3, row.getXh());
//						ps.setString(4, row.getFkzh());
//						ps.setString(5, row.getYhkd());
//						ps.setString(6, row.getPzh());
//
//						rs = ps.executeUpdate();
//
//						if (rs < 0) {
//							return;
//						}
//					}


        } catch (Exception e) {
            e.printStackTrace();
            res.setAlertMessage("数据推送浪潮失败");
        } finally {
            try {
                conn.close();
                ps.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        log.info("=========================退出-发票开具生成凭证结束=========================");
        return res;
    }
}
